﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text.Json;

using Contracts;
using ConfigHandle;
using Entities.ErrorModel;

namespace RemoteConfig.Controllers
{
    [Route("config")]
    [ApiController]
    public class RemoteJsonConfigController : ControllerBase
    {
        private readonly ILoggerManager _logger;
        private readonly IConfigManager _configManager;


        public RemoteJsonConfigController(ILoggerManager logger, IConfigManager configManager)
        {
            _logger = logger;
            _configManager = configManager;
        }

        [HttpGet]
        public IActionResult GetJsonFile()
        {
            var json = _configManager.GetJsonFile();

            return Ok(json);
        }


        [HttpGet("{key}")]
        public IActionResult GetJsonByKey(string key)  
        {
            // TODO:目前只针对一层
            // TODO: key == null ,合并
            var json = _configManager.GetJsonByKey(key);
            if (json==null)
            {
                return StatusCode(400, $"[GetJsonByKey] {key} not exist!");
            }

            return Ok(json);
        }


        [HttpPut]
        public IActionResult UpdateJson([FromBody] JsonElement body)
        {
            // input json string without "" https://stackoverflow.com/questions/58150652/asp-net-core-3-0-frombody-string-content-returns-the-json-value-could-not-be
            string json = System.Text.Json.JsonSerializer.Serialize(body);   // 
            _configManager.UpdateJson(json);
            return Ok();
        }


        [HttpPut("{key}")]
        public IActionResult UpdateJsonByKey(string key, [FromBody] JsonElement body)
        {
            //Console.WriteLine(body.GetType());
            //Console.WriteLine(body.GetInt32());
            //string json = System.Text.Json.JsonSerializer.Serialize(body);   // 
            _configManager.UpdateJsonByKey(key, body);

            return Ok();
        }



    }
}
